package com.insurance.handler.mybatisPlus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.insurance.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 *
 * mybatisplus 自动填充处理类,填充如时间等信息
 * @author qcjstudy
 * @create 2022-12-01 11:30
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId=null;
        try {
            userId = SecurityUtils.getUserId();
            System.out.println(userId);
        } catch (Exception e) {
            e.printStackTrace();
            userId=-1L;//表示自己创建，比如注册时还没有用户id
        }
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("createBy",userId,metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
        this.setFieldValByName("updateBy",userId,metaObject);
    }

    /**
     * 更新时填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
        this.setFieldValByName(" ",SecurityUtils.getUserId(),metaObject);
    }
}
